<?php
namespace app\admin\controller;

use app\common\controller\Admin;

class Version extends Admin
{
    //版本检测
	public function index()
    {
		$version = input('version/s');//本地版本号
        $module  = input('module/s','daicuo');//应用名称
        if(!$version){
			return json(array('code'=>0));
		}
        $json = \daicuo\Service::apiUpgrade(['event'=>'check','module'=>$module,'version'=>$version]);
		if($json['version']){
            if( version_compare($version, $json['version'], '<') ){
                if($module == 'daicuo'){
                    $upgrade = DcUrl('version/online');
                }else{
                    $upgrade = DcUrl('apply/upgrade',['module'=>$module]);
                }
                return json([
                    'code'    => 1,
                    'version' => $json['version'],
                    'msg'     => lang('update_down'),
                    'update'  => $json['update'],
                    'upgrade' => $upgrade,
                ]);
            }
		}
		return json(array('code'=>0));//版本一致
	}
    
    //手动升级需执行SQL
    public function upgrade()
    {
        $this->executeSql('upgrade');
        
        $this->success(lang('success'), 'index/index');
    }
    
    //手动卸载时执行SQL
    public function remove()
    {
        $this->executeSql('remove');
        
        $this->success(lang('success'), 'index/index');
    }
    
    //在线一键升级
    public function online()
    {
        //实例化文件类
        $file = new \files\File();
        //写入权限检查
        if(!$file->is_write('./temp')){
            $this->error( lang('web_create_failed') );
        }
        $file->d_delete('./temp');
        
        //下载补丁包到临时目录（会根据当前版本号自动返回对应的升级包，依次升级）
        $service = new \daicuo\Service();
        if(!$saveFile = $service->applyDownLoad(['event'=>'update','module'=>'daicuo','version'=>config('daicuo.version')])){
            $this->error( lang($service->getError()) );
        }

        //在线解压到根目录
        $zip = new \files\Zip();
        if(!$zip->unzip($saveFile, './')){
            $file->f_delete($saveFile);
            $this->error( lang('web_unzip_failed') );
        }
        
        //执行SQL脚本
        $this->executeSql('upgrade');
        
        //删除压缩包
        $file->f_delete($saveFile);
        
        //返回结果
        $this->success(lang('success'), 'index/index');
    }
    
    //执行SQL
    private function executeSql($method){
        //必要参数
        if(!$method){
            return true;
        }
        //无脚本文件
        if ( !class_exists('\\app\\sql') ){
            return true;
        }
        //实例化脚本类
        $sql = new \app\sql();
        //执行方法前方法是否已经定义 
        if( method_exists($sql, $method) ){
            return $sql->$method();
        }
        return true;
    }
}